package com.car.car.controller;


import com.car.car.domian.Result;
import com.car.car.domian.User;
import com.car.car.repository.UserRepository;
import com.car.car.service.UserService;
import com.car.car.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserService userService;

    private final static Logger logger = LoggerFactory.getLogger(UserController.class);
   @RequestMapping("")
    public List<User> getList()
    {
        return userRepository.findAll();
    }

    @PostMapping("/add")
    public Result<User> add(@Valid  User user, BindingResult bindingResult)
    {
        if(bindingResult.hasErrors()){
            return ResultUtil.error(1,bindingResult.getFieldError().getDefaultMessage());
        }
        user.setUsername(user.getUsername());
        user.setPassword(user.getPassword());
        user.setAge(user.getAge());
        return ResultUtil.success(userRepository.save(user));

    }

    @PostMapping("/delete")
    public void delete(@RequestParam("id") Integer id)
    {
            userRepository.delete(id);
    }


    @PostMapping("/update")
    public User update(@RequestParam("username") String username,@RequestParam("password") String password,
                        @RequestParam("id") Integer id
                        )
    {
        User user = new User();
        user.setId(id);
        user.setUsername(username);
        user.setPassword(password);
        return  userRepository.save(user);
    }


    @GetMapping("/{id}")
    public User getByid(@PathVariable("id") Integer id)throws Exception
    {
        userService.getAge(id);
        return userRepository.findOne(id);
    }


    @GetMapping("/username")
    public List<User> getByUsername(@RequestParam("username") String username)
    {
        return userRepository.findByUsername(username);
    }






}
